//
//  GSNewsTableViewController.m
//  GameSky
//
//  Created by lanou on 16/1/11.
//  Copyright © 2016年 NiRongfei. All rights reserved.
//

#import "GSNewsTableViewController.h"
#import "GSArticleViewController.h"
#import "GSNewsAdsCell.h"
#import "GSNewsMainCell.h"
#import "GSNewsImageCell.h"
#import "GSNewsChildElements.h"

#import <SDCycleScrollView.h>
#import <SDCollectionViewCell.h>
#import "UITableView+SDAutoTableViewCellHeight.h"

@interface GSNewsTableViewController ()<UIGestureRecognizerDelegate,SDCycleScrollViewDelegate>

@property (nonatomic, strong) NSMutableArray *sourceArray;

// 头部的轮播图数组
@property (nonatomic, strong) NSMutableArray *headImage;

/** 头部轮播标题 */
@property (nonatomic, strong) NSMutableArray *headTitle;

@property (nonatomic, strong) SDCycleScrollView *headview;

/** 存放专题 */
@property (nonatomic, strong) NSMutableArray *subjectArray;

@property (nonatomic, strong) NSMutableArray *sdCycleArray;

@property (nonatomic, assign) NSInteger  requestStrart;

@property(nonatomic,assign)BOOL update;


@end

@implementation GSNewsTableViewController


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    if (self.update == YES) {
        
        [self.tableView.mj_header beginRefreshing];
        self.update = NO;
    }
    
    [self.tableView.mj_header beginRefreshing];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // 夜间模式
    self.tableView.dk_backgroundColorPicker = DKColorWithRGB(0xffffff, 0x343434);
    
    self.update = YES;
    
    _requestStrart = 20;
    
    [self addData];
    
    
    /**
     *  下拉刷新
     */
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        _requestStrart = 20;
        
        [self addData];

    }];
    
    /**
     *  上拉刷新
     */
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        _requestStrart += 20;
        
        [self addData];
        
    }];
    

    [self.tableView registerClass:[GSNewsMainCell class] forCellReuseIdentifier:@"GSNewsMainCell"];
    
    [self.tableView registerClass:[GSNewsImageCell class] forCellReuseIdentifier:@"GSNewsImageCell"];

    [self.tableView registerClass:[GSNewsAdsCell class] forCellReuseIdentifier:@"GSNewsAdsCell"];
    
}

- (void)addData
{
    
    NSMutableDictionary *paraDict = [NSMutableDictionary dictionary];
    
    paraDict[@"deviceType"] = @"iPhone5,3";
    paraDict[@"deviceId"] = @"17E14E61-4069-4736-992D-EE596A7AECBC";
    paraDict[@"os"] = @"iOS";
    paraDict[@"osVersion"] = @"8.4";
    paraDict[@"app"] = @"GSApp";
    paraDict[@"appVersion"] = @"2.1.0";
    
    NSString *nodeIds = [NSString stringWithFormat:@"%@",self.nodeId];
    
    paraDict[@"request"] = @{@"parentNodeId":@"news", @"nodeIds":nodeIds, @"pageIndex":@"1", @"elementsCountPerPage":[NSString stringWithFormat:@"%ld",(long)_requestStrart] };
    
    [GSNetworkManager requestWithUrlStr:@"http://appapi2.gamersky.com/v2/AllChannelList" paraDict:paraDict method:POST success:^(NSURLResponse *response, NSData *data) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        if (_requestStrart == 1) {
            
            [_sourceArray removeAllObjects];
            
        }
        
        NSArray *array = dict[@"result"];
        
        self.sourceArray = [NSMutableArray array];
        self.subjectArray = [NSMutableArray array];
        self.headImage = [NSMutableArray array];        
        self.headTitle = [NSMutableArray array];
        self.sdCycleArray = [NSMutableArray array];
        
        for (NSDictionary *oneDic in array) {
            
            GSNewsListModel *newListModel = [[GSNewsListModel alloc]init];
            
            [newListModel setValuesForKeysWithDictionary:oneDic];
            
            if (newListModel.childElementsArray.count != 0) {
                
                if (![newListModel.type isEqualToString:@"zhuanti"]){
                
                for (GSNewsChildElements *child in newListModel.childElementsArray) {
                    
                    NSString *url = child.thumbnailURLsArray.firstObject;
                    
                    NSString *title = child.title;
                    
                    [_headImage addObject:url];
                    
                    [_headTitle addObject:title];
                    
                    [_sdCycleArray addObject:child.contentId];
                }
                }else{
                    
                    [self.subjectArray addObject:newListModel];
                    
                }
            }else{
                
                [self.sourceArray addObject:newListModel];
            }
        }
        
        /**
         *  头部的轮播图
         */
        [self addHeadScrollView];
        
        [self.tableView.mj_header endRefreshing];
        
        [self.tableView.mj_footer endRefreshing];
        
        [self.tableView reloadData];

    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];

    
}

// 头部的轮播图
- (void)addHeadScrollView
{
    _headview = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, kScreenWidth, 160) imageURLStringsGroup:self.headImage];
    
    _headview.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
    
    _headview.pageControlStyle = SDCycleScrollViewPageContolStyleClassic;
    
    _headview.delegate = self;
    _headview.titlesGroup = self.headTitle;
    
    self.tableView.tableHeaderView = _headview;
}

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    
    GSArticleViewController *detailVC = [[GSArticleViewController alloc]init];
    
    detailVC.contentID = self.sdCycleArray[index];
    
    
    [self.navigationController pushViewController:detailVC animated:YES];
    
    
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    // 开启 高度自适应
    [self.tableView startAutoCellHeightWithCellClasses:@[[GSNewsMainCell class],[GSNewsImageCell class]] contentViewWidth:[UIScreen mainScreen].bounds.size.width];
    
    if (section == 2 && self.subjectArray.count != 0) {
        
        GSNewsChildElements *child = self.subjectArray.firstObject;
        
        return child.thumbnailURLsArray.count;
        
        
    }
    
    
    return self.sourceArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    

    GSNewsListModel *model = self.sourceArray[indexPath.row];
    
    if ([model.type isEqualToString:@"xinwen"]) {
        
        GSNewsMainCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GSNewsMainCell" forIndexPath:indexPath];
        
        cell.model = model;
        
        return cell;
    }else if([model.type isEqualToString:@"santu"]) {
        
        GSNewsImageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GSNewsImageCell" forIndexPath:indexPath];
        
        cell.model = model;
        
        return cell;

        
    }else if ([model.type isEqualToString:@"hengtu"]){
        
        GSNewsAdsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GSNewsAdsCell" forIndexPath:indexPath];
        
        cell.model = model;
        
        return cell;
    }
    return nil;
}

/**
 *  返回cell的高度
 */
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    Class currentClass = [GSNewsMainCell class];
    
    GSNewsListModel *model = self.sourceArray[indexPath.row];
    
    if (model.thumbnailURLsArray.count > 1) {
        
        currentClass = [GSNewsImageCell class];
        
    }
    
    if ([model.type isEqualToString:@"hengtu"]) {
        
        currentClass = [GSNewsAdsCell class];
        
    }
    
    // 动态获得cell的高度
    return [self.tableView cellHeightForIndexPath:indexPath model:model keyPath:@"model" cellClass:currentClass];

    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSLog(@"ssss");
    
    GSArticleViewController *detailVC = [[GSArticleViewController alloc]init];
    
    GSNewsListModel *model = self.sourceArray[indexPath.row];
    
    
    if ([model.type isEqualToString:@"hengtu"]){
        
       [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms://itunes.apple.com/cn/app/tian-xiax-tian-xia-wang-yi/id931381852?mt=8&l=zh&ls=1&ign-mpt=uo%3D4"]];

    }else{

    
    
    detailVC.contentID = model.contentId;
    
    [tableView reloadData];
    
    [self.navigationController pushViewController:detailVC animated:YES];
    
    }
}



@end
